package com.supermap.dataservice.farmland;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.supermap.dataservice.agrinfo.dao.FarmingDao;
import com.supermap.dataservice.disaster.dao.DisasterDIPDao;
import com.supermap.dataservice.farmland.dao.FarmlandDao;
import com.supermap.dataservice.util.JSONUtil;
import com.supermap.dataservice.util.SortUtil;
import com.supermap.dubbo.api.agrinfo.entity.Farming;
import com.supermap.dubbo.api.disaster.entity.DisasterDIP;
import com.supermap.dubbo.api.farmland.FarmlandService;
import com.supermap.dubbo.api.farmland.entity.Farmland;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author:langhongshuai
 * @Description:
 * @Date:18/1/29 上午9:35
 */
@Service
public class FarmlandServiceImpl implements FarmlandService {
    /**
     * 使用指定类初始化日志对象，在日志输出的时候，可以打印出日志信息所在类
     */
    protected static final Logger logger = LoggerFactory.getLogger(FarmlandServiceImpl.class);

    @Resource
    private FarmlandDao farmlandDao;

    @Resource
    private FarmingDao farmingDao;

    @Resource
    private DisasterDIPDao disasterDIPDao;

    @Override
    public JSONUtil getFarmlandByUIdArea(String userId, String areaCode) {
        //初始化Json封装工具类
        JSONUtil jsonUtil = new JSONUtil();
        try {
            //获得用户所有的农田信息
            if(areaCode!=null){
                areaCode=areaCode+"%";
            }
            List<Farmland> farmlands = farmlandDao.getFarmlandByUIdArea(userId, areaCode);

            //获得用户所有的农田信息后返回的json数据
            jsonUtil.setMsg("Get user farmlands success！");
            jsonUtil.setIsSuccess(true);
            jsonUtil.setCode(200);
            jsonUtil.setData(farmlands);
        } catch (Exception e) {
            //捕捉数据库异常
            logger.error("FarmlandServiceImpl=>getFarmlandByUserId=>DaoException:" + e.getMessage());
            jsonUtil.setMsg("Get user farmlands flase！");
            jsonUtil.setIsSuccess(false);
            jsonUtil.setCode(100);
        }
        return jsonUtil;
    }

    @Override
    public JSONUtil addFarmland(Farmland farmland) {
        //初始化Json封装工具类
        JSONUtil jsonUtil = new JSONUtil();
        try {
            // 增加农田信息
            farmlandDao.addFarmland(farmland);
            //获得才增加的农田信息
            farmland.setId(farmlandDao.getFarmId());
            //增加农田作物信息关联表
            farmlandDao.addFarmCrops(farmland.getId(), farmland.getCrop());
            //增加农田信息后返回的json数据
            jsonUtil.setMsg("Add farmland success！");
            jsonUtil.setIsSuccess(true);
            jsonUtil.setCode(200);
            jsonUtil.setData(farmland);
        } catch (Exception e) {
            //捕捉数据库异常
            logger.error("FarmlandServiceImpl=>addFarmland=>DaoException:" + e.getMessage());
            jsonUtil.setMsg("Add farmland flase！");
            jsonUtil.setIsSuccess(false);
            jsonUtil.setCode(100);
        }
        return jsonUtil;
    }

    @Override
    public JSONUtil getFarmlandCountByArea(String[] areaCodes) {
        //初始化Json封装工具类
        JSONUtil jsonUtil = new JSONUtil();
        try {
            //获得用户所有的农田信息
            List<Map> data = farmlandDao.getFarmlandCountByArea(areaCodes);

            //获得用户所有的农田信息后返回的json数据
            jsonUtil.setMsg("Get user farmlands success！");
            jsonUtil.setIsSuccess(true);
            jsonUtil.setCode(200);
            jsonUtil.setData(data);
        } catch (Exception e) {
            //捕捉数据库异常
            logger.error("FarmlandServiceImpl=>getFarmlandCountByArea=>DaoException:" + e.getMessage());
            jsonUtil.setMsg("Get FarmlandCountByArea flase！");
            jsonUtil.setIsSuccess(false);
            jsonUtil.setCode(100);
        }
        return jsonUtil;
    }

    @Override
    public JSONUtil delFarmland(int farmlandId) {
        //初始化Json封装工具类
        JSONUtil jsonUtil = new JSONUtil();
        try {
            //获得用户所有的农田信息
            farmlandDao.delFarmland(farmlandId);

            //获得用户所有的农田信息后返回的json数据
            jsonUtil.setMsg("del user farmland success！");
            jsonUtil.setIsSuccess(true);
            jsonUtil.setCode(200);
            jsonUtil.setData(farmlandId);
        } catch (Exception e) {
            //捕捉数据库异常
            logger.error("FarmlandServiceImpl=>delFarmland=>DaoException:" + e.getMessage());
            jsonUtil.setMsg("del farmland flase！");
            jsonUtil.setIsSuccess(false);
            jsonUtil.setCode(100);
        }
        return jsonUtil;
    }

    @Override
    public JSONUtil getFramlandByCropIdAndAreaCode(String cropId, String areaCode) {
        //初始化Json封装工具类
        JSONUtil jsonUtil = new JSONUtil();
        try {
            //根据作物和区域获得所有的农田信息
            List<Farmland> farmlands = farmlandDao.getFramlandByCropIdAndAreaCode(cropId,areaCode);

            //根据作物和区域获得所有的农田信息后返回的json数据
            jsonUtil.setMsg("get farmlands success！");
            jsonUtil.setIsSuccess(true);
            jsonUtil.setCode(200);
            jsonUtil.setData(farmlands);
        } catch (Exception e) {
            //捕捉数据库异常
            logger.error("FarmlandServiceImpl=>getFramlandByCropIdAndAreaCode=>DaoException:" + e.getMessage());
            jsonUtil.setMsg("get farmlands flase！");
            jsonUtil.setIsSuccess(false);
            jsonUtil.setCode(100);
        }
        return jsonUtil;
    }

    @Override
    public JSONUtil getFarmLandDistribution(String areaCode) {
        //初始化Json封装工具类
        JSONUtil jsonUtil = new JSONUtil();
        try {
            //根据作物和区域获得所有的农田信息
            List<Farmland> farmlands = farmlandDao.getAllFarmland(areaCode);
            JSONObject jsonObject = new JSONObject();
            for (Farmland f:farmlands) {
                if(!jsonObject.containsKey(f.getAreaname())){
                    jsonObject.put(f.getAreaname(),1);
                }else {
                    jsonObject.put(f.getAreaname(),Integer.parseInt(jsonObject.get(f.getAreaname()).toString())+1);
                }
            }
            //根据作物和区域获得所有的农田信息后返回的json数据
            jsonUtil.setMsg("get farmLandDistribution success！");
            jsonUtil.setIsSuccess(true);
            jsonUtil.setCode(200);
            jsonUtil.setData(jsonObject);
        } catch (Exception e) {
            //捕捉数据库异常
            logger.error("FarmlandServiceImpl=>getFarmLandDistribution=>DaoException:" + e.getMessage());
            jsonUtil.setMsg("get farmLandDistribution flase！");
            jsonUtil.setIsSuccess(false);
            jsonUtil.setCode(100);
        }
        return jsonUtil;
    }

    @Override
    public JSONUtil getFarmingAndDIPInfoByFarmlandId(int farmlandid) {
        //初始化Json封装工具类
        JSONUtil jsonUtil = new JSONUtil();
        Set<String> keySets = new HashSet<>();
        List<String> keylist = new ArrayList<>();
        List<Object> list = new ArrayList<>();
        HashMap<String,Object> hashMap = new HashMap<>();
        try {
            //根据农田id获取农事信息和病虫害信息
            Farming parm = new Farming();
            parm.setFarmlandid(farmlandid);
            List<Farming> farmings = farmingDao.getFarming(parm);
            List<DisasterDIP> disasterDIPS = disasterDIPDao.getAllDisasterDIPByFarmlandId(farmlandid);
            for (Farming f:farmings) {
                keySets.add(f.getRecordtime());
            }
            for (DisasterDIP d:disasterDIPS) {
                keySets.add(d.getRecordtime());
            }
            //将所有的时间无重复的放入keysets里面
            keylist.addAll(keySets);
            //对时间进行排序
            SortUtil.quickSort(keylist,0,keylist.size()-1);
            hashMap.put("keys",keylist);
            //根据时间存储农事
            for (Farming f : farmings) {
                hashMap.put(f.getRecordtime(), f);
            }
            //根据时间存储病虫害信息
            for (DisasterDIP d : disasterDIPS) {
                hashMap.put(d.getRecordtime(), d);
            }
            for (int i=keylist.size()-1;i>=0;i--) {
                list.add(hashMap.get(keylist.get(i)));
            }
            //根据农田id获取农事信息和病虫害信息后返回的json数据
            jsonUtil.setMsg("get farming and DIP success！");
            jsonUtil.setIsSuccess(true);
            jsonUtil.setCode(200);
            jsonUtil.setData(list);
        } catch (Exception e) {
            //捕捉数据库异常
            logger.error("FarmlandServiceImpl=>getFarmingAndDIPInfoByFarmlandId=>DaoException:" + e.getMessage());
            jsonUtil.setMsg("get farming and DIP flase！");
            jsonUtil.setIsSuccess(false);
            jsonUtil.setCode(100);
        }
        return jsonUtil;
    }

    @Override
    public JSONUtil getAllDisasterDIPByCCodeAndUId(String cropCode,int userId) {
        //初始化Json封装工具类
        JSONUtil jsonUtil = new JSONUtil();
        Set<String> keySets = new HashSet<>();
        List<String> keylist = new ArrayList<>();
        List<Object> list = new ArrayList<>();
        HashMap<String,Object> hashMap = new HashMap<>();
        try {
            //根据作物code获取农事信息和病虫害信息
            Farming parm = new Farming();
            parm.setCroptype(cropCode);
            parm.setUserid(userId);
            List<Farming> farmings = farmingDao.getFarming(parm);
            List<DisasterDIP> disasterDIPS = disasterDIPDao.getAllDisasterDIPByCCodeAndUId(cropCode,userId);
            for (Farming f:farmings) {
                keySets.add(f.getRecordtime());
            }
            for (DisasterDIP d:disasterDIPS) {
                keySets.add(d.getRecordtime());
            }
            //将所有的时间无重复的放入keysets里面
            keylist.addAll(keySets);
            //对时间进行排序
            SortUtil.quickSort(keylist,0,keylist.size()-1);
            hashMap.put("keys",keylist);
            //根据时间存储农事
            for (Farming f : farmings) {
                hashMap.put(f.getRecordtime(), f);
            }
            //根据时间存储病虫害信息
            for (DisasterDIP d : disasterDIPS) {
                hashMap.put(d.getRecordtime(), d);
            }
            for (int i=keylist.size()-1;i>=0;i--) {
                list.add(hashMap.get(keylist.get(i)));
            }
            //根据作物code获取农事信息和病虫害信息后返回的json数据
            jsonUtil.setMsg("get farming and DIP success！");
            jsonUtil.setIsSuccess(true);
            jsonUtil.setCode(200);
            jsonUtil.setData(list);
        } catch (Exception e) {
            //捕捉数据库异常
            logger.error("FarmlandServiceImpl=>getAllDisasterDIPByCCodeAndUId=>DaoException:" + e.getMessage());
            jsonUtil.setMsg("get farming and DIP flase！");
            jsonUtil.setIsSuccess(false);
            jsonUtil.setCode(100);
        }
        return jsonUtil;
    }

    @Override
    public JSONUtil getCropsByUserId(String userId) {
        //初始化Json封装工具类
        JSONUtil jsonUtil = new JSONUtil();
        try {
            List<Farmland> farmlands = farmlandDao.getFarmlandByUId(userId);
            HashMap<String,Farmland> hashMap = new HashMap<>();
            for (Farmland f:farmlands) {
               hashMap.put(f.getCrop(),f);
            }
            Collection<Farmland> farmlandCollection = hashMap.values();
            List list = new ArrayList();
            list.addAll(farmlandCollection);
            //获得用户所有的农田里的作物种类信息后返回的json数据
            jsonUtil.setMsg("Get user crops success！");
            jsonUtil.setIsSuccess(true);
            jsonUtil.setCode(200);
            jsonUtil.setData(list);
        } catch (Exception e) {
            //捕捉数据库异常
            logger.error("FarmlandServiceImpl=>getCropsByUserId=>DaoException:" + e.getMessage());
            jsonUtil.setMsg("Get user crops flase！");
            jsonUtil.setIsSuccess(false);
            jsonUtil.setCode(100);
        }
        return jsonUtil;
    }

    @Override
    public JSONUtil updateFarmland(Farmland farmland) {
        //初始化Json封装工具类
        JSONUtil jsonUtil = new JSONUtil();
        Date date = new Date();
        farmland.setUpdateTime(date);
        try {
            farmlandDao.updateFarmland(farmland);
            //修改农田信息后返回的json数据
            jsonUtil.setMsg("update farmland success！");
            jsonUtil.setIsSuccess(true);
            jsonUtil.setCode(200);
            jsonUtil.setData(farmland);
        } catch (Exception e) {
            //捕捉数据库异常
            logger.error("FarmlandServiceImpl=>updateFarmland=>DaoException:" + e.getMessage());
            jsonUtil.setMsg("update farmland flase！");
            jsonUtil.setIsSuccess(false);
            jsonUtil.setCode(100);
        }
        return jsonUtil;
    }

}